import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router'
import { useUserAuthStore } from "../stores/userStore"

const routes: Array<RouteRecordRaw> = [
  {
    path: '/',
    component: () => import('../views/login.vue')
  },
  {
    path: "/test",
    component: () => import('../views/test.vue')
  },
  {
    path: '/index',
    component: () => import('../views/index.vue'),
    meta: { requireAuth: true },
    redirect: '/index/myexam',
    children: [
      {
        path: 'myexam',
        component: () => import('../views/myexams.vue'),
        meta: { requiresAuth: true }
      },
      {
        path: 'history',
        component: () => import('../views/history.vue'),
        meta: { requiresAuth: true }
      },
      {
        path: 'getHistory',
        component: () => import('../views/getHistory.vue'),
        meta: { requiresAuth: true }
      },
      {
        path: 'examResult',
        component: () => import('../views/examResult.vue'),
        meta: { requiresAuth: true },
      },
      {
        name: 'answerSheet',
        path: 'answerSheet/:examId',
        component: () => import('../views/answerSheet.vue'),
        meta: { requiresAuth: true }
      },
      {
        name: "ranklist",
        path: "ranklist/:examId",
        component: () => import('../views/ranklist.vue'),
      }
    ]
  },
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 路由守卫
router.beforeEach((to, from, next) => {
  const userStore = useUserAuthStore()
  let token = sessionStorage.getItem('token')
  if (to.matched.some(record => record.meta.requiresAuth)) {
    if ((userStore.token === "" && userStore.username === "") && token === "") {
      next({
        path: '/',
        query: { redirect: to.fullPath }
      })
    } else {
      next()
    }
  } else {
    next()
  }
})

export default router
